<?php

class Database_Mysql {

  protected $_connect;

  public function __construct($config) {

    $this->_connect = mysql_pconnect($config['host'], $config['username'], $config['password']);
    mysql_select_db($config['dbname'], $this->_connect);
  }

  public function query($sql) {
    echo $sql;
    Logger::write($sql);
    return mysql_query($sql);
  }

  public function insert($model, $entity, $mode='') {
    $pk = $model->pk();
    $fields = $model->fields();
    $data = array();

    foreach ($fields as $f) {
      $value = @$entity->{$f};
      if ($value == NULL) {
        $data[$f] = 'NULL';
      } else {
        $data[$f] = "'" . mysql_escape_string($value) . "'";
      }
    }
    $sql = sprintf('INSERT %s INTO %s (`%s`) VALUES (%s);', $mode, $model->table(), implode('`,`', $fields), implode(" , ", $data));
    if (($result = $this->query($sql)) != NULL) {
      if ($pk == 'id') {
        $entity->{$pk} = mysql_insert_id();
      }
      return $entity;
    }
    return false;
  }

  public function update($model, $entity) {
    
  }

  public function delete($model, $entity) {
    
  }

  public function find($model, $query) {
    
  }

}
